package com.easylinkin.sm.adapter;

import com.easylinkin.sm.constant.UserConstant.Error;
import com.easylinkin.sm.entity.Department;
import com.easylinkin.sm.entity.Role;
import com.easylinkin.sm.service.UserService;

import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import site.morn.bean.annotation.Target;
import site.morn.exception.ApplicationMessages;
import site.morn.validate.persistent.DeleteValidation;

/**
 * 用户相关校验
 *
 * @author TianGanLin
 * @since 0.1.1, 2019/4/19
 */
@Component
public class RelateUserValidation {

  /**
   * 用户服务
   */
  @Resource
  private UserService userService;

  /**
   * 组织机构删除校验
   */
  @Component
  @Target(Department.class)
  public class DeleteDepartment implements DeleteValidation<Department> {

    @Override
    public void validate(Department department) {
      Assert.notNull(department, "组织机构不能为空");
      if (userService.existsByDepartment(department.getId())) { // 判断组织机构是否绑定用户
        throw ApplicationMessages.translate(Error.DELETE_DEPARTMENT).exception();
      }
    }
  }

  /**
   * 角色删除校验
   */
  @Component
  @Target(Role.class)
  public class DeleteRole implements DeleteValidation<Role> {

    @Override
    public void validate(Role role) {
      Assert.notNull(role, "角色不能为空");
      if (userService.existsByRole(role.getId())) { // 判断角色是否绑定用户
        throw ApplicationMessages.translate(Error.DELETE_ROLE).exception();
      }
    }
  }
}
